package com.feihong.yw189.fragment.shouye;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.AppUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.dtr.settingview.lib.SettingView;
import com.dtr.settingview.lib.entity.SettingData;
import com.dtr.settingview.lib.entity.SettingViewItemData;
import com.dtr.settingview.lib.item.BasicItemViewH;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.kaika.moneyout.AddMoneyActivity;
import com.feihong.yw189.activity.kaika.moneyout.BalanceTurnOutActivity;
import com.feihong.yw189.activity.yonghuzhongxin.AboutUsActivity;
import com.feihong.yw189.activity.yonghuzhongxin.FeedBackActivity;
import com.feihong.yw189.activity.yonghuzhongxin.MySettingActivity;
import com.feihong.yw189.activity.yonghuzhongxin.wodexiaoxi.MessageListActivity;
import com.feihong.yw189.activity.yonghuzhongxin.wodexiaoxi.ShareActivity;
import com.feihong.yw189.activity.yonghuzhongxin.wodexiaoxi.SystemNoticeActivity;
import com.feihong.yw189.activity.yonghuzhongxin.zhuanzhang.AddMoneyDetailActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.dialog.ServiceDialogFragment;
import com.feihong.yw189.fragment.base.BaseFragment;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.model.User.UserEntity;
import com.feihong.yw189.model.User.my.ZhuanZhang;
import com.feihong.yw189.utils.MessageEvent;
import com.feihong.yw189.utils.UserLoginInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import ezy.boost.update.UpdateManager;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Sabirjan on 2017/11/13.
 * DX189.
 * 飞宏电子
 * 首页---->个人中心
 */
@RuntimePermissions
public class GeRenZhongXinFragment extends BaseFragment {
    @BindView(R.id.my_head_photo)
    CircleImageView myHeadPhoto;
    @BindView(R.id.my_head_name)
    TextView myHeadName;
    @BindView(R.id.my_head_phone)
    TextView myHeadPhone;
    @BindView(R.id.my_account_img)
    ImageView myAccountImg;
    @BindView(R.id.my_account_money)
    TextView myAccountMoney;
    @BindView(R.id.my_account_info)
    ImageView myAccountInfo;
    @BindView(R.id.ll_account)
    LinearLayout llAccount;
    @BindView(R.id.my_freez_info)
    ImageView myFreezInfo;
    @BindView(R.id.ll_freez)
    LinearLayout llFreez;
    @BindView(R.id.tv_jfnum)
    ImageView tvJfnum;
    @BindView(R.id.ll_ydetail)
    LinearLayout llYdetail;  //加款记录layout
    @BindView(R.id.my_info_setview) //消息|公告 adapter
            SettingView myInfoSetview;
    @BindView(R.id.my_app_setview) //帮助类 adapter
            SettingView myAppSetview;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.img_btn_setting)
    ImageButton imgBtnSetting;
    @BindView(R.id.img_btn_servers)
    ImageButton imgBtnServers;
    @BindView(R.id.title_layout)
    LinearLayout titleLayout;
    @BindView(R.id.my_btn_zhuangzhang)
    Button myBtnZhuangzhang;
    @BindView(R.id.my_btn_jiakuan)
    Button myBtnJiakuan;
    @BindView(R.id.my_dongjie)
    TextView myDongjie;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refreshLayout;

    public static final String TAG = "营维189";
    public View fragmentView = null;
    Unbinder unbinder;
    private SettingData mItemData = null;
    private SettingViewItemData mItemViewData = null;
    private List<SettingViewItemData> mListData = new ArrayList<SettingViewItemData>();
    private List<SettingViewItemData> mListAppData = new ArrayList<SettingViewItemData>();
    private ServiceDialogFragment dialog;

    public static GeRenZhongXinFragment newInstance(String tabName) {
        GeRenZhongXinFragment geRenZhongXinFragment = new GeRenZhongXinFragment();
        geRenZhongXinFragment.tag = tabName;
        return geRenZhongXinFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.fragment_rerenzhongxin, container, false);
        unbinder = ButterKnife.bind(this, fragmentView);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return fragmentView;
    }

    @Override
    protected void setTheme() {

    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        //获取个人信息
        initView();
        bindData();
    }

    @Override
    public void initView() {
        txtTitle.setText("我的");
        imgBtnServers.setVisibility(View.VISIBLE);
        refreshLayout.setColorSchemeResources(R.color.appBlue);
        mItemData = new SettingData();
        mItemData.setTitle("我的消息");
        mItemData.setTitleSize(14);

        //这里应该返回用户未读消息数量
        int readNum = UserLoginInfo.getUserLoginInfoInstance().getReadInfoNum();
        if (readNum > 0) {
            mItemData.setSubTitle("" + readNum);
            mItemData.setSubTitleSize(12);
        }

        mItemData.setDrawable(getResources().getDrawable(R.mipmap.my_message));

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemData = new SettingData();
        mItemData.setTitle("平台公告");
        mItemData.setTitleSize(14);
        mItemData.setDrawable(getResources().getDrawable(R.mipmap.my_notice));

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemData = new SettingData();
        mItemData.setTitle("分享二维码");
        mItemData.setTitleSize(14);
        mItemData.setDrawable(getResources().getDrawable(R.mipmap.share));

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);


        myInfoSetview.setAdapter(mListData);

        // settingview的点击事件
        myInfoSetview.setOnSettingViewItemClickListener(index -> {
                if (isFastDoubleClick(SettinglastClickTime)) {
                    return;
                }
                SettinglastClickTime = System.currentTimeMillis();
                switch (index) {
                    case 0:
                        //我的消息
                        Intent intent = new Intent(_mActivity, MessageListActivity.class);
                        startActivity(intent);
                        break;
                    case 1:
                        //平台公告
                        Intent intentNotice = new Intent(_mActivity, SystemNoticeActivity.class);
                        startActivity(intentNotice);
                        break;

                    case 2:
                        //分享二维码
                        Intent intentShare = new Intent(_mActivity, ShareActivity.class);
                        startActivity(intentShare);
                        break;

                    default:
                        break;
            }
        });

        mItemData = new SettingData();
        mItemData.setTitle("意见反馈");
        mItemData.setTitleSize(14);
        mItemData.setDrawable(getResources().getDrawable(R.mipmap.my_feedback));

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListAppData.add(mItemViewData);

        mItemData = new SettingData();
        mItemData.setTitle("关于我们");
        mItemData.setTitleSize(14);
        mItemData.setDrawable(getResources().getDrawable(R.mipmap.my_aboutus));

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListAppData.add(mItemViewData);

        mItemData = new SettingData();
        mItemData.setTitle("客服电话");
        mItemData.setTitleSize(14);
        mItemData.setDrawable(getResources().getDrawable(R.mipmap.my_service));

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListAppData.add(mItemViewData);

        mItemData = new SettingData();
        mItemData.setTitle("版本号");
        mItemData.setTitleSize(14);
        mItemData.setSubTitle("" + AppUtils.getAppVersionName());
        mItemData.setSubTitleSize(12);
        mItemData.setDrawable(getResources().getDrawable(R.mipmap.my_version));

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListAppData.add(mItemViewData);

        myAppSetview.setAdapter(mListAppData);

        // settingview的点击事件
        myAppSetview.setOnSettingViewItemClickListener(index ->  {
                if (isFastDoubleClick(SettinglastClickTime)) {
                    return;
                }
                SettinglastClickTime = System.currentTimeMillis();
                switch (index) {
                    case 0:
                        //意见反馈
                        startActivity(new Intent(_mActivity, FeedBackActivity.class));
                        break;
                    case 1:
                        //关于我们
                        startActivity(new Intent(_mActivity, AboutUsActivity.class));
                        break;
                    case 2:
                        //客服电话
                        servicePhone();
                        break;
                    case 3:
                        //设置默认更新接口地址与渠道
                        UpdateManager.setUrl(HttpTools.UPDATE_APP, "Android");
                        UpdateManager.setWifiOnly(false);
                        // 在设置界面点击检查更新
                        UpdateManager.checkManual(getActivity());
                        break;
                    default:
                        break;
            }
        });

        refreshLayout.setOnRefreshListener(() -> getUserInfo());

        // 转出点击事件
        myBtnZhuangzhang.setOnClickListener(v ->  {
                //转出
            startActivity(new Intent(_mActivity, BalanceTurnOutActivity.class));

        });

        // 加款点击事件
        myBtnJiakuan.setOnClickListener(v ->  {
                //加款
                startActivity(new Intent(_mActivity, AddMoneyActivity.class));
        });

    }

    private void getZhuanzhang() {
        App.getApp().getHttpTools().getZhuanZhang(new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i(TAG, "onSuccess: " + result);
                try {
                    if (!TextUtils.isEmpty(result)) {
                        ZhuanZhang zhuanzhang = JSON.parseObject(result, ZhuanZhang.class);

                        if (zhuanzhang.getStatus() == 1) {
                            if (zhuanzhang.getData().getIs_zhuanzhang() == 1) {
                            } else {
                                showErrorToast("" + zhuanzhang.getInfo());
                                myBtnZhuangzhang.setVisibility(View.GONE);
                            }
                        } else {
                            showErrorToast("" + zhuanzhang.getInfo());
                        }
                    }
                } catch (Exception ex) {
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                showToast("请检查网络");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    @Override
    public void bindData() {
        //头像显示
        UserEntity userInfo = UserLoginInfo.getUserLoginInfoInstance().getUserLoc();
        String userPic = userInfo.getUserPic();
        if (!TextUtils.isEmpty(userPic)) {
            Glide.with(_mActivity).load(userInfo.getUserPic()).apply(new RequestOptions().placeholder(R.mipmap.my_setting_photo)).into(myHeadPhoto);
        }
        //名称
        String headName = userInfo.getUserName();
        if (!TextUtils.isEmpty(headName)) {
            myHeadName.setText(userInfo.getUserName());
        }
        //手机
        String headPhone = userInfo.getUserName();
        if (!TextUtils.isEmpty(headPhone)) {
            String userPhone = userInfo.getUserMobile();
            if (userPhone.length() == 11) {
                userPhone = userPhone.substring(0, 3) + "****" + userPhone.substring(7);
            }
            myHeadPhone.setText(userPhone);
        }
        String dongjie = userInfo.getUserFreezingBalance();
        if (TextUtils.isEmpty(dongjie)) {
            myDongjie.setText("冻结:未知");
        } else {
            myDongjie.setText("冻结:" + new DecimalFormat("#.##").format(Double.parseDouble(dongjie)));
        }
        String yue = userInfo.getUserAccountBalance();
        if (TextUtils.isEmpty(yue)) {
            myAccountMoney.setText("0");
        } else {
            myAccountMoney.setText("" + new DecimalFormat("#.##").format(Double.parseDouble(yue)));
        }
        String transOut = userInfo.getBalaceTransOutPermission();
        if (!TextUtils.isEmpty(transOut) && transOut.equals("1")) {
            myBtnZhuangzhang.setVisibility(View.VISIBLE);
        } else {
            myBtnZhuangzhang.setVisibility(View.GONE);
        }
    }

    //获取用户信息
    private void getUserInfo() {
        //获取用户信息
        App.getApp().getHttpTools().userInfo(new RequestCallBack() {
            @Override
            public void onSuccess(Object result) {
                try {
                    parseJson("" + result);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                showToast("请检查网络");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {
                if (refreshLayout != null) {
                    refreshLayout.setRefreshing(false);
                }
            }
        });
    }

    @OnClick({R.id.img_btn_setting, R.id.ll_ydetail, R.id.ll_account})
    public void onViewClicked(View view) {
        if (isFastDoubleClick(OtherlastClickTime)) {
            return;
        }
        OtherlastClickTime = System.currentTimeMillis();
        int id = view.getId();
        Intent intent = new Intent();
        switch (id) {
            case R.id.img_btn_setting:
                intent.setClass(_mActivity, MySettingActivity.class);
                break;
            case R.id.ll_account:
                intent.putExtra("typeDefine", 1);
                intent.setClass(_mActivity, AddMoneyDetailActivity.class);
                break;
            case R.id.ll_ydetail:
                intent.putExtra("typeDefine", 3);
                intent.setClass(_mActivity, AddMoneyDetailActivity.class);
                break;
            default:
                break;
        }

        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    //用户信息解析
    private void parseJson(String jsonStr) {
        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            String resultCode = jsonObject.optString("status");
            if (resultCode.equals("1")) {
                UserEntity userEntity = new UserEntity();
                JSONObject personInfoData = jsonObject.optJSONObject("data");
                if (personInfoData != null) {
                    userEntity.setUserID(personInfoData.optString("user_id"));
                    userEntity.setUserName(personInfoData.optString("user_name"));
                    userEntity.setUserEmail(personInfoData.optString("email"));
                    userEntity.setUserMobile(personInfoData.optString("mobile"));
                    userEntity.setUserType(personInfoData.optString("user_type"));
                    userEntity.setUserStatus(personInfoData.optString("status"));
                    userEntity.setFaceReadSign(personInfoData.optString("face_read"));
                    String transAccountSign = personInfoData.optString("is_zhuanzhang");
                    userEntity.setTransToAccountPermission(transAccountSign);
                    if (transAccountSign.equals("1")) {
                        myBtnZhuangzhang.setVisibility(View.VISIBLE);
                    } else {
                        myBtnZhuangzhang.setVisibility(View.GONE);
                    }
                    userEntity.setBalaceTransOutPermission(personInfoData.optString("is_zhuanchu"));
                    userEntity.setReissueCardPermission(personInfoData.optString("reissue_card"));
                    userEntity.setPlatFormTel(personInfoData.optString("reissue_card"));
                    JSONObject personal = personInfoData.optJSONObject("personal");
                    if (personal != null) {
                        userEntity.setUserIDCardName(personal.optString("real_name"));
                        userEntity.setUserIDCardNum(personal.optString("idcard"));
                        userEntity.setUserSex(personal.optString("sex"));
                        userEntity.setUserPic(personal.optString("user_img"));
                        userEntity.setUserTel(personal.optString("tel"));
                        userEntity.setUsrQQ(personal.optString("qq"));
                        userEntity.setUserAccountManagerName(personal.optString("contact_name"));
                        userEntity.setUserAccountManagerContactTel(personal.optString("contact_tel"));
                        userEntity.setUsrAdr(personal.optString("address"));
                        userEntity.setUserStoreAccount(personal.optString("dj_account"));
                    }
                    JSONObject money = personInfoData.optJSONObject("money");
                    if (money != null) {
                        userEntity.setUserWalletStatus(money.optString("state"));
                        userEntity.setUserAliPayAccount(money.optString("alipay_account"));
                        userEntity.setAliPayRate(money.optString("alipay_rate"));
                    }
                    JSONObject bankInfo = personInfoData.optJSONObject("money_bank");
                    if (bankInfo != null) {
                        userEntity.setUserBankNum(bankInfo.optString("bank_num"));
                        userEntity.setUserBankName(bankInfo.optString("open_bank"));
                        userEntity.setUserBankCardAccountName(bankInfo.optString("open_name"));
                        userEntity.setUserBankRate(bankInfo.optString("bank_rate"));
                    }
                    JSONObject balance = personInfoData.optJSONObject("balance");
                    if (balance != null) {
                        userEntity.setUserAccountBalance(balance.optString("money"));
                        userEntity.setUserFreezingBalance(balance.optString("freeze_money"));
                    }
                    JSONObject verify = personInfoData.optJSONObject("extension");
                    if (verify != null) {
                        userEntity.setUserVerifyMobileSign(verify.optString("is_mobile"));
                        userEntity.setUserVerifyEmailSign(verify.optString("is_email"));
                        userEntity.setUserVerifyRealNameSign(verify.optString("is_user"));
                    }
                    JSONObject region = personInfoData.optJSONObject("region");
                    if (region != null) {
                        userEntity.setUserRegionID(region.optString("parent_id"));
                        userEntity.setUserReginName(region.optString("region_name"));
                    }
                    JSONObject agent = personInfoData.optJSONObject("agent");
                    if (agent != null) {
                        userEntity.setUserAgentUserID(agent.optString("user_id"));
                        userEntity.setUserAgentUserName(agent.optString("user_name"));
                        userEntity.setUserAgentUserEmail(agent.optString("email"));
                    }
                    JSONObject agentP = personInfoData.optJSONObject("agent_p");
                    if (agentP != null) {
                        userEntity.setUserAgentTel(agentP.optString("tel"));
                        userEntity.setUserAgentUserImg(agentP.optString("user_img"));
                    }
                    UserLoginInfo.getUserLoginInfoInstance().saveUserLoginInfo(userEntity);
                    bindData();
                }
            } else {
                showToast(jsonObject.optString("info"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //EventBus 回调通知,修改设置信息
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        switch (event.getType()) {
            case MessageEvent.EDIT_NAME:
                myHeadName.setText(UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserName());
                break;
            case MessageEvent.EDIT_PHONE:
                String userPhone = UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserMobile();
                if (userPhone.length() == 11) {
                    userPhone = userPhone.substring(0, 3) + "****" + userPhone.substring(7);
                }
                myHeadPhone.setText(userPhone);
                break;
            case MessageEvent.EDIT_PHOTO:
                Glide.with(_mActivity).load(UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserPic()).into(myHeadPhoto);
                break;
            case MessageEvent.CALL_PER:
//               showErrorToast("电话权限");
                GeRenZhongXinFragmentPermissionsDispatcher.needPermissionWithCheck(this);
                break;
            default:
                break;
        }
    }

    private void servicePhone() {

        dialog = new ServiceDialogFragment(_mActivity);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);// 屏蔽点击空拍dialog消失
        dialog.showDialog();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private static long SettinglastClickTime;
    private static long OtherlastClickTime;

    private static boolean isFastDoubleClick(long lastClickTime) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 1000 * 2) {
            return true;
        }
        return false;
    }

    @NeedsPermission(Manifest.permission.CALL_PHONE)
    void needPermission() {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        GeRenZhongXinFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.CALL_PHONE)
    void show(final PermissionRequest request) {
        new AlertDialog.Builder(_mActivity)
                .setPositiveButton("允许", (mDialog,whitch) -> request.proceed())
                .setNegativeButton("拒绝", (mDialog,which) -> request.cancel())
                .setCancelable(false)
                .setMessage("请允许获取拨打电话权限")
                .show();
    }

    @OnNeverAskAgain(Manifest.permission.CALL_PHONE)
    void askAgain() {
        showErrorDialog("权限不足", "您没有开启此应用的使用拨打电话权限。请到系统设置-->权限管理 开启拨打电话使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下拨打电话权限！"
                ,dialog -> { });
    }
}
